const cloud = require('wx-server-sdk');

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
});
const db = cloud.database();
const _ = db.command

exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const data = event.data
  const user = await db.collection("user").where({
    "openid": wxContext.OPENID,
  }).get()

  if (user.data.length == 0) {
    return {
      code: 401,
      data: {},
      msg: "have not login"
    }
  }

  if (user.data[0].status != 0 && user.data[0].status != 1) {
    return {
      code: 401,
      data: {},
      msg: "no privilege"
    }
  }
  let audit_time=new Date()
  let task = []

  for (let i in data) {
    if (data[i].state == 0)//成功
    {
      task.push(
        db.collection("order").doc(data[i]._id).update({
          data: {
            state: 0,
            audit_time:audit_time
          }
        })
      )
    }
    else//失败
    {
      if (data[i].fail_reason == null)//没给原因
      {
        task.push(db.collection("order").doc(data[i]._id).update({
          data: {
            state: 1,
            fail_reason: "管理员没有给出原因",
            audit_time:audit_time
          }
        }))
      }
      else//给原因了
      {
        task.push(
          db.collection("order").doc(data[i]._id).update({
            data: {
              state: 1,
              fail_reason: data[i].fail_reason,
              audit_time:audit_time
            }
          })
        )
      }
      let buf = await db.collection("order").doc(data[i]._id).get()

      const res = await db.collection("timeTable").where({
        timestamp: buf.data.timestamp
      }).update({
        data: {
          number: _.inc(-1)
        }
      })
    }
  }

  const result = await Promise.all(task)

  return {
    code: 200,
    data: result,
    msg: "success",
    audit:audit_time
  }

};
